import datetime
from prometheus_api_client import PrometheusConnect, MetricsList
class KubePrometheus:
    def __init__(self, url="http://172.20.216.103:13103") -> None:
        self.prom = PrometheusConnect(url=url)
    def _parse_chunk_size(self, chunk_size):
        if chunk_size.endswith('s'):
            return datetime.timedelta(seconds=int(chunk_size[:-1]))
        elif chunk_size.endswith('m'):
            return datetime.timedelta(minutes=int(chunk_size[:-1]))
        elif chunk_size.endswith('h'):
            return datetime.timedelta(hours=int(chunk_size[:-1]))
        elif chunk_size.endswith('d'):
            return datetime.timedelta(days=int(chunk_size[:-1]))
        else:
            raise ValueError('非法时间格式。 请以s/m/h/d结尾（分别对应seconds/minutes/hours/days）。')
        
    def _get_metric_data_range(self,  metric_name, label_config, start_time=datetime.datetime.now() - datetime.timedelta(minutes=10), end_time=datetime.datetime.now(), step='30s'):
        metric_data = self.prom.get_metric_range_data(metric_name=metric_name, label_config=label_config, start_time=start_time, end_time=end_time, chunk_size=self._parse_chunk_size(step))
        return metric_data
    def get_node_memory_usage(self,  node='k8s-master001',minutes=10,step='30s'):
        """  
        node: 节点名称
        minutes: 时间范围
        step: 时间间隔,以s/m/h/d结尾（分别对应seconds/minutes/hours/days）
        return: 节点内存使用情况
        """
        # 获取最近10分钟k8s-master001节点的内存使用情况
        metric_name='node_memory_MemAvailable_bytes'
        my_label_config = {'instance': node, 'job': 'node-exporter'}
        
        start_time = datetime.datetime.now() - datetime.timedelta(minutes=minutes)
        
        metric_data = self._get_metric_data_range(metric_name, my_label_config, start_time=start_time, step=step)
        return [(item['metric']['instance'], item['values']) for item in metric_data]


if __name__ == '__main__':
    kube_prometheus = KubePrometheus()
    nodes = ['k8s-master001', 'k8s-node001', 'k8s-node03']
    # for node in nodes:
    data = kube_prometheus.get_node_memory_usage('k8s-master001', minutes=1, step='20s')
    print(data)